<template>
  <t-dialog
      header="运行测试用例"
      :visible.sync="showDialogRun"
      @confirm="onConfirm"
      :confirmOnEnter="true"
      :onConfirm="onConfirmAnother"
      :onCancel="onCancel"
      :onEscKeydown="onKeydownEsc"
      :onCloseBtnClick="onClickCloseBtn"
      :onOverlayClick="onClickOverlay"
      :onClose="close"
      width='60%'
    >
    <t-space size="32px">
    <t-form
      :data="formData"
      labelWidth="calc(2em + 100px)"
      :layout="layout"
      ref="form"
      scrollToFirstError="smooth"
      width='400%'
    >
    <t-form-item v-if="isBatch" label="测试用例" style="margin-top: 20px;">
        <t-input v-model="formData.testcase_name" :readonly="true" style="margin-right: 10px;width: 300px;"></t-input>
        <t-input v-model="formData.git_addr"  :readonly="true" style="width: 300px;"></t-input>
    </t-form-item>
    <t-form-item v-else label="测试用例" style="margin-top: 20px;" v-for="(item, index) in testCaseList" :key="index">
        <t-input v-model="item.testcasename" :readonly="true" style="margin-right: 10px;width: 300px;"></t-input>
        <t-input v-model="item.testcasegitaddr"  :readonly="true" style="width: 300px;"></t-input>
    </t-form-item>
    <t-form-item label="测试链" style="margin-top: 20px;">
      <div class="cascader-demo-panel-container">
        <t-cascader-panel class="t-cascader__menu"
        v-model="nodeListSelected" 
        :options="nodeList"
        :value="value"
        multiple
        size="large"
        >
        <!-- <t-select
          v-model="inputProps"
          :style="{ width: '222px' }"
          class="demo-select-base"
          placeholder="请选择类型"
          clearable
        >
          <t-option v-for="(item, index) in inputProps" :key="index + item.path" :value="item.chain_id" :label="item.chain_conn_name">
            {{ item.chain_conn_name }}
          </t-option> -->
        <!-- </t-select> --> 
        </t-cascader-panel>
      </div>
    </t-form-item>
    </t-form>
  </t-space>
  </t-dialog>
</template>

<script lang="jsx">
import { getChainConnList, operateTestCase } from '@/api/requestApi'

const INITIAL_FORM_DATA = {
  testcase_id: undefined,
  testcase_name: '',
  node_list: [],
  chain_conn_id: undefined,
  chain_conn_name: '',
  git_addr: '',
};
const FORM_RULES = {
  chain_conn_name: [{ required: true, message: '请选择所属模块', type: 'error' }],
  node_list: [{ required: true, message: '请选择优先级', type: 'error' }],
};

export default {
  name: 'RunDialogComp',
  components: {

  },
  props: {
    showChildDialogRun: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      nodeList: [],
      nodeListItem: {
        value: '',
        label: '',
        children: [
          {label: '', value: ''},
        ]
      },
      nodeListSelected: [],
      value:[],
      data: [],
      inputProps: {
        value: this.data,
      },
      layout: 'vertical', // 纵向布局
      formData: {...INITIAL_FORM_DATA},
      FORM_RULES: {...FORM_RULES},
      isBatch: '',
      testCaseList: [],
    };
    
  },
  
  computed: {
    showDialogRun: {
      get() {
        return this.showChildDialogRun
      },
      set(newValue) {
        this.$emit('update:showChildDialogRun', newValue) // 触发更新事件，父组件的showDialogAdd会自动更新
      }
    },
  },
  mounted() {
    this.dataLoading = true;
    this.$request
      .get(getChainConnList())
      .then((res) => {       
        if (res.data.code === '000') {
          const list = res.data.data;
          this.data = list;
          // console.log('data--->',this.data)
          this.data.forEach(item => {
            const arr = {children:[]}
            arr.value = item.id.toString();
            arr.label = item.name;
            let i = 1;
            JSON.parse(item.node_list).forEach(element =>{
              const arr2 = {};
              arr2.label = `${element.node_name}:${element.node_addr}`;
              arr2.value = `${item.id}.${i}`;
              i += 1;
              arr.children.push(arr2);
            });
            this.nodeList.push(arr);
          });
          // console.log('nodeList->', this.nodeList)
          this.pagination = {
            ...this.pagination,
            total: list.length,
          };
        } else {
          this.$message.error(res.data.msg);
        }
      })
      .catch((e) => {
        this.$message.error(e);
        console.log(e);
      })
      .finally(() => {
        this.dataLoading = false;
      });
  },
  methods: {
    init(data) {
      // this.showDialog=true;
      // data是父组件弹窗传递过来的值，我们可以打印看看
      this.formData = data;
      this.isBatch = true;
      console.log('来自父组件的', data);
    },
    initBatch(testCaseList) {
      // this.showDialog=true;
      // data是父组件弹窗传递过来的值，我们可以打印看看
      // this.formData = data
      this.isBatch = false;
      this.testCaseList = testCaseList;
      console.log('批量-来自父组件的', this.formData, testCaseList);
    },
    onConfirm() {
      this.dataLoading = true;
      const chainConnList = [];  
      this.nodeListSelected.forEach(value => {
        const chain_conn_id = value.split('.')[0]; 
        let chainObj = null;
        for(let i=0; i<chainConnList.length; i++){
          if(chainConnList[i].chain_conn_id === chain_conn_id){
            chainObj = chainConnList[i];
          }
        }
        if(chainObj == null){
          chainObj = {'chain_conn_id': chain_conn_id, 'node_list': []};
          chainConnList.push( chainObj );
        }
        this.nodeList.forEach(nl => {
          nl.children.forEach(nll => {
            if(nll.value === value){
              const nodeListVar = {
                'node_name': nll.label.split(':')[0], 
                'node_addr': `${nll.label.split(':')[1]}:${nll.label.split(':')[2]}`
              };
              chainObj.node_list.push(nodeListVar);
            }
          })         
        })
      }); 
      const reqParam = {};
      const ids = [];
      if (this.formData.testcase_id && this.testCaseList.length === 0){
        ids.push(this.formData.testcase_id.toString());
      } else if (!this.formData.testcase_id && this.testCaseList.length > 0){
        this.testCaseList.forEach(item =>{
          ids.push(item.testcaseid.toString())
        })
      }
      reqParam.param = chainConnList;
      reqParam.op_type = '3';
      reqParam.ids = ids;
      // 发起请求
      this.$request
        .post(operateTestCase(),reqParam)
        .then((res) => {
          if (res.data.code === '000') {
            this.$message.success('测试用例运行成功');
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.showDialogRun = false;
      // this.$emit('runFlush')
    },
    onConfirmAnother() {
      this.showDialogRun = false;
      // this.$emit('runFlush')
      // console.log('点击了确认按钮');
    },
    close() {
      this.showDialogRun = false;
      // this.$emit('addOrUpdateVisible', false)
      // console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发');
    },
    onCancel() {
      this.showDialogRun = false;
      // console.log('点击了取消按钮');
    },
    onKeydownEsc() {
      this.showDialogRun = false;
      // console.log('按下了ESC');
    },
    onClickCloseBtn() {
      this.showDialogRun = false;
      // console.log('点击了关闭按钮');
    },
    onClickOverlay() {
      this.showDialogRun = false;
      // console.log('点击了蒙层');
    },
  },
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';
.cascader-demo-panel-container {
  border: 1px solid #eee;
  width: 100%;
}
/deep/ .t-cascader__menu {
  width: auto;
}
</style>
